package com.hc.appanimal;

import static com.hc.appanimal.ServerTask.DISPLAY_MESSAGE_ACTION;
import static com.hc.appanimal.ServerTask.EXTRA_MESSAGE;
import static com.hc.appanimal.ServerTask.SENDER_ID;
import static com.hc.appanimal.ServerTask.TAG;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import com.google.android.gcm.GCMRegistrar;
import com.hc.DTO.TokenDTO;
import com.hc.model.utils.TokenModel;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class Main extends Activity implements OnClickListener {
	Button btnLogin, btnRegister;
	AsyncTask<Void, Void, Void> gcmRegisterTask;
	final BroadcastReceiver handleMessageReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
			setResultCode(Activity.RESULT_OK);
			Log.i(TAG, newMessage);
		}
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		btnLogin = (Button) findViewById(R.id.btnLogin);
		btnRegister = (Button) findViewById(R.id.btnRegister);
		btnLogin.setOnClickListener(this);
		btnRegister.setOnClickListener(this);

		TokenModel tokenModel = TokenModel.getInstance();
		TokenDTO tokenDTO = tokenModel.getToken(Main.this);
		String dateExpires = tokenDTO.getExpires();

		Date date2 = null;
		Date date1 = null;
		String pattern = "EEE, dd MMM yyyy HH:mm:ss Z";
		SimpleDateFormat format = new SimpleDateFormat(pattern, Locale.ENGLISH);
		String currentDayExpires = format.format(new Date());
		xuLyDangKyGCMServer();
		try {
			date1 = format.parse(currentDayExpires);
			date2 = format.parse(dateExpires);
			if (date1.compareTo(date2) < 0) {
				
				Intent intent = new Intent(Main.this, LoginActivity.class);
				startActivity(intent);
				finish();
			}
		} catch (Exception e) {
		}

	}

	@Override
	public void onClick(View v) {
		Intent intent;
		switch (v.getId()) {
		case R.id.btnRegister:
			intent = new Intent(Main.this, MainActivity.class);
			startActivity(intent);
			break;
		case R.id.btnLogin:
			intent = new Intent(Main.this, LoginActivity.class);
			startActivity(intent);

			break;
		default:
			break;
		}

	}
	
	protected void xuLyDangKyGCMServer() {
		// Make sure the device has the proper dependencies.
		GCMRegistrar.checkDevice(Main.this);
		// Make sure the manifest was properly set - comment out this
		// line
		// while developing the app, then uncomment it when it's ready.
		GCMRegistrar.checkManifest(Main.this);

		// msg = (TextView) findViewById(R.id.display);

		registerReceiver(handleMessageReceiver, new IntentFilter(
				DISPLAY_MESSAGE_ACTION));
		final String regId = GCMRegistrar.getRegistrationId(Main.this);

		if (regId.equals("")) {
			// Automatically registers application on startup.
			GCMRegistrar.register(Main.this, SENDER_ID);
		} else {
			// Device is already registered on GCM, check server.
			if (GCMRegistrar.isRegisteredOnServer(Main.this)) {
				// Skips registration.
				// msg.append(getString(R.string.already_registered) +
				// "\n");
				;
				final Context context = Main.this;
				gcmRegisterTask = new AsyncTask<Void, Void, Void>() {

					@Override
					protected Void doInBackground(Void... params) {
						boolean registered = ServerTask.register(context,
								regId);
						// At this point all attempts to register with
						// the
						// app
						// server failed, so we need to unregister the
						// device
						// from GCM - the app will try to register again
						// when
						// it is restarted. Note that GCM will send an
						// unregistered callback upon completion, but
						// GCMIntentService.onUnregistered() will ignore
						// it.
						if (!registered) {
							GCMRegistrar.unregister(context);
						}
						return null;
					}

					@Override
					protected void onPostExecute(Void result) {
						gcmRegisterTask = null;
					}

				};
				gcmRegisterTask.execute(null, null, null);
			} else {
				// Try to register again, but not in the UI thread.
				// It's also necessary to cancel the thread onDestroy(),
				// hence the use of AsyncTask instead of a raw thread.
				final Context context = Main.this;
				gcmRegisterTask = new AsyncTask<Void, Void, Void>() {

					@Override
					protected Void doInBackground(Void... params) {
						boolean registered = ServerTask.register(context,
								regId);
						// At this point all attempts to register with
						// the
						// app
						// server failed, so we need to unregister the
						// device
						// from GCM - the app will try to register again
						// when
						// it is restarted. Note that GCM will send an
						// unregistered callback upon completion, but
						// GCMIntentService.onUnregistered() will ignore
						// it.
						if (!registered) {
							GCMRegistrar.unregister(context);
						}
						return null;
					}

					@Override
					protected void onPostExecute(Void result) {
						gcmRegisterTask = null;
					}

				};
				gcmRegisterTask.execute(null, null, null);
			}
		}

	}
}
